<?php
namespace Modules\Good\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Comment\Http\Resources\CommentResource;

class GoodResource extends JsonResource
{
    public function toArray($request)
    {
        // 将 include 参数拆分成数组
        $includes = explode(',', $request->query('include', ''));
        $data = [
            'id' => $this->id,
            'user_id' => $this->user_id,
            'category_id' => $this->category_id,
            'title' => $this->title,
            'description' => $this->description,
            'price' => $this->price,
            'stock' => $this->stock,
            'cover' => $this->cover,
            'pics' => $this->pics,
            'detail' => $this->detail,
            'is_on' => $this->is_on,
            'is_recommend' => $this->is_recommend,
            'created_at' => $this->created_at,
        ];

        // 如果请求 include=category，并且模型已加载 category 关系且分类存在
        if (in_array('category', $includes) && $this->relationLoaded('category') && $this->category) {
            $data['category'] = [
                'id' => $this->category->id,
                'name' => $this->category->name,
            ];
        }

        // 如果请求 include=user，并且模型已加载 user 关系且用户存在
        if (in_array('user', $includes) && $this->relationLoaded('user') && $this->user) {
            $data['user'] = [
                'id' => $this->user->id,
                'name' => $this->user->name,
                'email' => $this->user->email,
            ];
        }
        if (in_array('comments', $includes) && $this->relationLoaded('comments')) {
            $data['comments'] = CommentResource::collection($this->comments);
        }

        return $data;
    }


}
